/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.dao;

import com.entities.Account;
import com.utilities.DBUtil;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Min Tun
 */
public class AccountDAO {

    public static void main(String[] args){
        System.out.println(checkLogin("locmxse60602", "123456").isAdmin());
    }

    public static Account checkLogin(String username, String password){
        Account result = new Account();
        // Result set
        ResultSet rs = null;
        // 1, Connect to database and prepare SQL query
        Connection con = DBUtil.getConnection();
        String query = "select * from Account where account = ? and password = ?";
        try {
            // 2. Prepare statement
            PreparedStatement stm = con.prepareStatement(query);
            stm.setString(1, username);
            stm.setString(2, password);

            rs = stm.executeQuery();

            while(rs.next()){
                result.setAccount(rs.getString("account"));
                result.setDisplayName(rs.getString("display_name"));
                result.setAdmin(rs.getBoolean("isAdmin"));
            }

        } catch (SQLException ex) {
            Logger.getLogger(AccountDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }

    public static int addAccount(Account account) {
        int status = 0;

        Connection con = DBUtil.getConnection();
        String query = "insert into Account(account, password, display_name, joined_date, isMale, isAdmin) " +
                "values(?, ?, ?, ?, ?, ?)";
        try {
            PreparedStatement stm = con.prepareCall(query);
            stm.setString(1, account.getAccount());
            stm.setString(2, account.getPassword());
            stm.setString(3, account.getDisplayName());
            stm.setDate(4, new java.sql.Date(account.getJoinedDate().getTime()));
            stm.setBoolean(5, account.isMale());
            stm.setBoolean(6, account.isAdmin());

            status = stm.executeUpdate();

        } catch (SQLException ex) {
            Logger.getLogger(AccountDAO.class.getName()).log(Level.SEVERE, null, ex);
        }


        return status;
    }

    

}
